<?php
// 接口-库存余额
namespace interface\v1;

class inventoryOtherClass extends index
{
	private const        page       = 'inventoryBalance';
	private const        table      = 'inventory_record';
	private const        tableInv   = 'inventory';
	private const        tableInvMx = 'inventory_detail';
	private const        title      = '库存余额';
	
	/**
	 * 账套列表
	 *
	 * @return void
	 */
	public function company(): void
	{
		$this->code         = 1;
		$result             = find(['table' => 'company', 'field' => 'coid as value, name as text']);
		$this->resp['data'] = [
			'option' => $result['array'],
			'now'    => self::findCoid(),
		];
	}
	
	/**
	 * 查找当前使用的coid
	 *
	 * @return mixed
	 */
	public static function findCoid(): mixed
	{
		$record = query('user_setting', "stid = '" . self::$stid . "' and type = '当前使用账套'");
		if (empty($record['id'])) {
			$company = query('company', "isDel = 0");
			self::updateCoidRecord($company['coid']);
			self::$coid = $company['coid'];
			return $company['coid'];
		}
		return $record['value'];
	}
	
	/**
	 * 记录当前使用的账套
	 */
	public static function updateCoidRecord($coid): bool
	{
		if (empty($coid)) {
			return false;
		}
		$record = query('user_setting', "stid = '" . self::$stid . "' and type = '当前使用账套'");
		if (empty($record['id'])) {
			$warn = static::insert(array(
				'table' => 'user_setting',
				'field' => [
					'type'  => '当前使用账套',
					'value' => $coid,
					'stid'  => self::$stid,
				],
			));
		} else {
			$warn = static::update(array(
				'table' => 'user_setting',
				'field' => [
					'value' => $coid,
				],
				'where' => "id = '$record[id]'",
			));
		}
		return in_array($warn, ['新增成功', '更新成功']);
	}
	
	
	public function getDefaultFunc()
	{
		$this->code = 1;
		$record     = query('user_setting', "stid = '" . self::$stid . "' and type = 'ERP小程序常用功能'");
		if (!empty($record['id'])) {
			$this->resp['data'] = json_decode($record['value'], true);
		} else {
			static::insert(array(
				'table' => 'user_setting',
				'field' => [
					'type'  => 'ERP小程序常用功能',
					'value' => '{}',
					'stid'  => self::$stid,
				],
			));
			$this->resp['data'] = json_decode('{}');
		}
	}
	
	/**
	 * 更新默认功能
	 */
	public function upDefaultFunc()
	{
		$value = $_POST['func'] ?: '{}';
		$array = json_decode($value, true);
		if (!is_array($array)) {
			$this->resp['warn'] = '更新失败';
		} else {
			$func   = json_encode($array, 320);
			$record = query('user_setting', "stid = '" . self::$stid . "' and type = 'ERP小程序常用功能'");
			if (empty($record['id'])) {
				$warn = static::insert(array(
					'table' => 'user_setting',
					'field' => [
						'type'  => 'ERP小程序常用功能',
						'value' => $func,
						'stid'  => self::$stid,
					],
				));
			} else {
				$warn = static::update(array(
					'table' => 'user_setting',
					'field' => [
						'value' => $func,
					],
					'where' => "id = '$record[id]'",
				));
			}
			if (in_array($warn, ['新增成功', '更新成功'])) {
				$this->resp['warn'] = '更新成功';
				$this->resp['data'] = $array;
				$this->code         = 1;
			} else {
				$this->resp['warn'] = '更新失败';
			}
		}
	}
	
	/**
	 * 切换账套
	 *
	 * @return void
	 */
	public function setCompany(): void
	{
		$coid = $this->post('coid');
		if (!$coid) {
			$this->resp['warn'] = '请选择账套';
		} else {
			$bool = self::updateCoidRecord($coid);
			if ($bool !== true) {
				$this->resp['warn'] = '账套选择失败';
			} else {
				$this->resp['warn'] = '选择成功';
				$this->code         = 1;
			}
		}
	}
	
	/**
	 * 列表仓库
	 *
	 * @return void
	 */
	public function warehouse(): void
	{
		$this->code = 1;
		if(empty(self::$coid)){
			self::$coid = self::findCoid();
		}
		$result     = find(['table' => 'warehouse', 'field' => 'id as value, name as text', 'where' => " state = '启用' AND coid = '" . self::$coid . "' "]);
		$this->resp['data'] = $result['array'];
	}
	
	/**
	 * 供应商
	 *
	 * @return void
	 */
	public function supplier(): void
	{
		$this->code         = 1;
		$result             = find(['table' => 'supplier', 'field' => 'id as value, name as text', 'where' => "state = '启用' AND coid = '" . self::$coid . "' "]);
		$this->resp['data'] = $result['array'];
	}
	
	/**
	 * 加工单类型
	 *
	 * @return void
	 */
	public function machiningType(): void
	{
		$this->code         = 1;
		$this->resp['data'] = ['生产加工', '生产返工'];
	}
	
	/**
	 * 客户
	 *
	 * @return void
	 */
	public function kehu(): void
	{
		$this->code         = 1;
		$result             = find(['table' => 'kehu', 'field' => 'khid as value, companyName as text', 'where' => " (coid = '" . self::$coid . "' or coid = '') and isDeal = 1 "]);
		$this->resp['data'] = $result['array'];
	}
	
	/**
	 * 选择员工
	 */
	public function staff()
	{
		$this->code         = 1;
		$result             = find([
			'field' => 'stid as value, name as text',
			'table' => 'staff',
		]);
		$this->resp['data'] = $result['array'];
	}
	
	/**
	 * 物料分类
	 *
	 * @return void
	 */
	public function materialType(): void
	{
		$this->code         = 1;
		$result             = find([
			'table' => 'material_type',
			'field' => " id as value, name as text ",
			'where' => generateWhere([
				'coid' => self::$coid,
			]),
		]);
		$this->resp['data'] = $result['array'];
	}
	
	/**
	 * 物料品牌
	 *
	 * @return void
	 */
	public function materialBrand(): void
	{
		$this->code         = 1;
		$result             = find([
			'table' => 'material',
			'field' => "DISTINCT(brand) as text, id as value ",
			'where' => generateWhere([
					'coid'  => self::$coid,
					'state' => '启用',
				]) . " AND brand <> '' ",
		]);
		$this->resp['data'] = $result['array'];
	}
	
	/**
	 * 选择生产线
	 *
	 * @return void
	 */
	public function line(): void
	{
		$this->code         = 1;
		$where              = search([
			'=' => [
				'workshop' => $this->post('workshop') ?: '',
			],
		]);
		$field              = $where ? ' id as value, name as text ' : 'distinct workshop as text';
		$result             = find([
			'table' => 'product_line',
			'field' => $field,
			'where' => generateWhere([
					'coid'  => self::$coid,
					'state' => '启用',
				]) . $where,
		]);
		$this->resp['data'] = $result['array'];
	}
	
	/**
	 * 待办数量
	 *
	 * @return void
	 */
	public function backlog(): void
	{
		$this->code         = 1;
		$this->resp['data'] = [
			'backlog' => self::total([
				'table' => 'backlog',
				'where' => " stid = '" . self::$stid . "' AND workFlow = '待处理' AND startDay <='" . $this->date . "' ",
			]),
			'message' => self::total([
				'table' => 'message',
				'where' => " stid = '" . self::$stid . "' AND see = '否' ",
			]),
		];
	}
	
	/**
	 * 待办list
	 *
	 * @return void
	 */
	public function backlogList(): void
	{
		$this->code         = 1;
		$act                = $this->post('act');
		$result             = match ($act) {
			default   => $this->page([
				'table' => 'backlog',
				'where' => " stid = '" . self::$stid . "' AND workFlow = '待处理' AND startDay <='" . $this->date . "' ",
				'order' => 'time desc',
			]),
			'message' => $this->page([
				'table' => 'message',
				'where' => " stid = '" . self::$stid . "' AND see = '否' ",
				'order' => 'time desc',
			])
		};
		$this->resp['data'] = [
			'result' => $result['array'],
			'page'   => $result['para'],
		];
	}
	
	public function dataBoard()
	{
		/**
		 * 金额单位格式化
		 *
		 * @param $money
		 * @return string
		 */
		function moneyUnit($money): string
		{
			return $money > 10000 ? round(($money / 10000), 2) . '万' : round($money, 2);
		}
		
		$this->code = 1;
		$date       = $this->post('date');
		//销售金额
		$where = " and coid = '" . self::$coid . "' ";
		if ($date) {
			$where .= $this->timeComparison($date, 'date', 'recordDate');
		}
		$income = find(['table' => 'sale_order', 'where' => "state = '已确认'" . $where, 'sum' => "money"]);
		
		//回款金额
		$where = " and b.coid = '" . self::$coid . "' ";
		if ($date) {
			$where .= $this->timeComparison($date, 'date', 'b.recordDate');
		}
		$refundMoney = find(array('table' => "receipt_source as a join receipt as b on a.orderId = b.id", "single" => " b.state = '已确认' and b.classify = 1 " . $where, 'sum' => "money"));
		//核销单
		$refundMoney += find(array('table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id", "single" => " b.state = '已确认' and b.type = '预收冲应收' " . $where, 'sum' => "money"));
		
		$deliveryRate       = str_replace('%', '', inventoryDefaultClass::deliveryRate('按期交货率', $date));
		$this->resp['data'] = [
			[
				'type'  => '销售金额',
				'money' => moneyUnit($income),
			],
			[
				'type'  => '回款金额',
				'money' => moneyUnit($refundMoney),
			],
			[
				'type'  => '毛利润',
				'money' => moneyUnit(inventoryDefaultClass::costProfit('毛利润', $date)),
			],
			[
				'type'  => '毛利率',
				'money' => moneyUnit(inventoryDefaultClass::costProfit('毛利率', $date)),
			],
			[
				'type'  => '按期交货率',
				'money' => moneyUnit($deliveryRate) . '%',
			],
		];
	}
	
	
	public function func()
	{
		$imgSrc        = root . 'img/miniProgram/erp/';
		$this->code    = 1;
		$items['功能'] = [
			'saleOrder'           => [
				'name' => '销售订单',
				'icon' => $imgSrc . 'sales.svg',
				'url'  => '/pages/sales/index',
			],
			'processReport'       => [
				'name' => '工序报工',
				'icon' => $imgSrc . 'processReport.svg',
				'url'  => '/pages/processReport/index',
			],
			'materialInspection'  => [
				'name' => '来料检验',
				'icon' => $imgSrc . 'materialInspection.svg',
				'url'  => '/pages/materialInspection/index',
			],
			"outsourceInspection" => [
				"name" => "委外入库检验",
				'icon' => $imgSrc . 'outsourceInspection.svg',
				'url'  => '/pages/outsourceInspection/index',
			],
			'inStock'             => [
				'name' => '入库',
				'icon' => $imgSrc . 'instock.svg',
				'url'  => '/pages/instock/index',
			],
			'outStock'            => [
				'name' => '出库',
				'icon' => $imgSrc . 'outstock.svg',
				'url'  => '/pages/outstock/index',
			],
			"moveStock"           => [
				"name" => "移库",
				'icon' => $imgSrc . 'moveStock.svg',
				'url'  => '/pages/moveStock/index',
			],
			'inventoryBalance'    => [
				'name' => '库存查询',
				'icon' => $imgSrc . 'inventoryQuery.svg',
				'url'  => '/pages/inventory/index',
			],
		];
		$items['统计'] = [
			'salesReportForm'     => [
				'name' => '销售统计',
				'icon' => $imgSrc . 'saleStatistics.svg',
				'url'  => '/pages/saleStatistics/index',
			],
			'purchaseReportForm'  => [
				'name' => '采购统计',
				'icon' => $imgSrc . 'purchaseStatistics.svg',
				'url'  => '/pages/purchaseStatistics/index',
			],
			'machiningOrder'      => [
				'name' => '生产统计',
				'icon' => $imgSrc . 'machiningStatistics.svg',
				'url'  => '/pages/machiningStatistics/index',
			],
			'quarantine'          => [
				'name' => '质检统计',
				'icon' => $imgSrc . 'quarantineStatistics.svg',
				'url'  => '/pages/quarantineStatistics/index',
			],
			'inventoryReportForm' => [
				'name' => '库存统计',
				'icon' => $imgSrc . 'inventoryStatistics.svg',
				'url'  => '/pages/inventoryStatistics/index',
			],
		];
		// 数据
		// $items['销售'] = [
		// 	'saleOrder' => [
		// 		'name' => '销售订单',
		// 		'icon' => $imgSrc . 'sales.svg',
		// 		'url'  => '/pages/sales/index',
		// 	],
		// ];
		// $items['采购'] = [
		// 	'purchaseApply' => [
		// 		'name' => '采购申请',
		// 		'icon' => $imgSrc . 'purchase.svg',
		// 		'url'  => '/pages/purchase/index',
		// 	],
		// 	'purchaseOrder' => [
		// 		'name' => '采购统计',
		// 		'icon' => $imgSrc . 'purchaseStatistics.svg',
		// 		'url'  => '/pages/purchaseStatistics/index',
		// 	],
		// ];
		// $items['生产'] = [
		// 	'machiningOrder'   => [
		// 		'name' => '生产计划单',
		// 		'icon' => $imgSrc . 'machiningOrder.svg',
		// 		'url'  => '/pages/machiningOrder/index',
		// 	],
		// 	'machiningInOrder' => [
		// 		'name' => '生产入库单',
		// 		'icon' => $imgSrc . 'machiningInOrder.svg',
		// 		'url'  => '/pages/machiningInOrder/index',
		// 	],
		// 	'processReport'    => [
		// 		'name' => '工序报工',
		// 		'icon' => $imgSrc . 'processReport.svg',
		// 		'url'  => '/pages/processReport/index',
		// 	],
		// 	'productTrack'     => [
		// 		'name' => '生产统计',
		// 		'icon' => $imgSrc . 'machiningStatistics.svg',
		// 		'url'  => '/pages/machiningStatistics/index',
		// 	],
		// ];
		// $items['库存'] = [
		// 	'inStock'          => [
		// 		'name' => '入库',
		// 		'icon' => $imgSrc . 'instock.svg',
		// 		'url'  => '/pages/instock/index',
		// 	],
		// 	'outStock'         => [
		// 		'name' => '出库',
		// 		'icon' => $imgSrc . 'outstock.svg',
		// 		'url'  => '/pages/outstock/index',
		// 	],
		// 	'inventoryBalance' => [
		// 		'name' => '库存查询',
		// 		'icon' => $imgSrc . 'inventoryQuery.svg',
		// 		'url'  => '/pages/inventory/index',
		// 	],
		// ];
		$array = [];
		foreach ($items as $title => $pages) {
			$temp = [];
			foreach ($pages as $page => $item) {
				if ($this->power($page, 'see')) {
					$temp[] = $item;
				}
			}
			if (empty($temp)) {
				continue;
			}
			$array[] = [
				'title' => $title,
				'array' => $temp,
			];
		}
		$this->resp['data'] = $array;
	}
	
	/**
	 * 查找物料
	 *
	 * @return void
	 */
	public function codeByMaterial(): void
	{
		$code = $this->post('code') ?: '';
		$id   = $this->post('orderId') ?: '';
		$waid = $this->post('waid') ?: '';
		$from = $this->post('from') ?: '';
		if (self::isNull($code)) {
			$this->resp['warn'] = '物料条码不能为空';
		} else {
			$materialSku = query('material_sku', " coid = '" . self::$coid . "' AND barcode = '$code' ");
			if (self::isNull($materialSku['id'])) {
				$this->resp['warn'] = '当前账套不存在该物料，请确认';
				return;
			}
			$material     = query('material', " id = '{$materialSku['materialId']}' ");
			$inventoryNum = inventoryBalanceClass::inventoryNum($materialSku['id'], $waid);
			$result       = [
				'mxId'          => self::getId(),
				'materialSkuId' => $materialSku['id'],
				'code'          => $material['code'],
				'name'          => $material['name'],
				'brand'         => $material['brand'],
				'model'         => $material['model'],
				'skuName'       => $materialSku['name'],
				'unit'          => $material['unit'],
				'unitOption'    => inventoryBalanceClass::materialUnit($materialSku['id']),
			];
			$info         = [];
			if ($id && $from) {
				switch ($from) {
					case '入库单':
					case '出库单':
						$table = 'inventory';
						$info  = query($table, " id = '$id' ", 'id, orderNo, IFNULL(orderDate, time) as orderDate, classify, targetId, text');
						if ($info['classify'] == 0) {
							$info['target'] = query('kehu', " khid = '{$info['targetId']}' ")['companyName'];
						} else {
							$info['target'] = query('supplier', " id = '{$info['targetId']}' ")['name'];
						}
						break;
					case '盘点单':
						$table         = 'inventory_take';
						$info          = query($table, " id = '$id' ", 'id, orderNo, warehouse, type as typeId, brand, orderDate, text');
						$info['mtype'] = $info['typeId'] ? inventoryClass::getTypeName($info['typeId']) : null;
						unset($info['typeId']);
						break;
					case '调拨单':
						$table = 'inventory_allot';
						$info  = query($table, " id = '$id' ", 'id, orderNo, outWarehouse, inWarehouse, orderDate');
						break;
					default:
						$this->resp['warn'] = '类型错误';
						return;
				}
				
				if (self::isNull($info['id'])) {
					$this->resp['warn'] = '此订单信息不存在';
					return;
				}
				$detail = query($table . '_detail', " orderId = '{$info['id']}' AND materialSkuId = '$materialSku[id]' ");
				if (self::isNull($detail['id'])) {
					$this->resp['warn'] = '该订单不存在此物料信息';
					return;
				}
				$result['mxId'] = $detail['id'];
				$result         = array_merge($result, [
					'num'          => $detail['num'],
					'inventoryNum' => $inventoryNum,
					'orderNum'     => $detail['orderNum'] ?: 0,
				]);
			}
			$this->resp['data'] = [
				'info'   => $info,
				'result' => $result,
			];
			$this->code         = 1;
		}
	}
	
	/**
	 * 查找单号
	 *
	 * @return void
	 */
	public function orderByNo(): void
	{
		$orderNo = $this->post('orderNo') ?: '';
		if (self::isNull($orderNo)) {
			$this->resp['warn'] = '单号不能为空';
		} else {
			// 调拨
			if (str_contains($orderNo, 'DB') === true) {
				$info      = query('inventory_allot', " orderNo = '$orderNo' ");
				$source    = 'inventoryAllot';
				$aliasName = '调拨单';
			} // 盘点
			elseif (str_contains($orderNo, 'PD') === true) {
				$info      = query('inventory_take', " orderNo = '$orderNo' ");
				$source    = 'inventoryTake';
				$aliasName = '盘点单';
			} else {
				$info      = query('inventory', " orderNo = '$orderNo' ");
				$source    = 'inventory';
				$aliasName = ($info['classify'] == 0) ? '出库单' : '入库单';
			}
			
			if (self::isNull($info['id'])) {
				$this->resp['warn'] = '单号信息不存在';
			} else {
				$data               = [
					'info'   => $info,
					'source' => $source,
					'from'   => $aliasName,
				];
				$this->resp['data'] = $data;
				$this->code         = 1;
			}
		}
	}
	
}
